# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

head=ListNode(1,None)
head.next=ListNode(2,None)
head.next.next=ListNode(3,None)
head.next.next.next=ListNode(4,None)
head.next.next.next.next=ListNode(5,None)
left=2
right=4
def reverseBetween(head,left, right):
    #创建一个默认的头结点（空头结点）
    ans=ListNode()
    ansProcess=ans
    ans_left_right_head=None
    head_process=head
    headProcessIndex=1
    while head_process!=None:
        #工作结点
        newProcess=ListNode(head_process.val,None)
        if headProcessIndex<left:
            #开头部分
            #尾插法
            ansProcess.next=newProcess
            ansProcess=ansProcess.next
        elif headProcessIndex>=left and headProcessIndex<=right:
            #头插法部分
            if headProcessIndex==left:
                #第一个插入的位置，这个位置也是 headProcessIndex>right时的起始点位置
                newProcess.next=ansProcess.next
                ansProcess.next=newProcess
                #记录一下这个位置
                ans_left_right_head=newProcess
            elif headProcessIndex>left and headProcessIndex<right:
                newProcess.next=ansProcess.next
                ansProcess.next=newProcess
            else:
                newProcess.next=ansProcess.next
                ansProcess.next=newProcess
                ansProcess=ans_left_right_head
        else:
            #后面部分依旧使用尾插法
            ansProcess.next=newProcess
            ansProcess=ansProcess.next
        head_process=head_process.next
        headProcessIndex+=1
    ansProcess=ans
    while ansProcess!=None:
        print(ansProcess.val)
        ansProcess=ansProcess.next
    return ans.next
reverseBetween(head,left,right)
